package com.weitu.contractor.controller;

import com.weitu.accessory.util.AccessoryUtil;
import com.weitu.base.annotaion.SystemLog;
import com.weitu.base.controller.BaseController;
import com.weitu.contractor.entity.BusinessQualification;
import com.weitu.contractor.entity.BusinessQualificationCriteria;
import com.weitu.contractor.entity.BusinessQualificationHistory;
import com.weitu.contractor.entity.BusinessQualificationHistoryCriteria;
import com.weitu.contractor.service.BusinessQualificationHistoryService;
import com.weitu.contractor.service.BusinessQualificationService;
import com.weitu.paging.DataGridPagination;
import com.weitu.plugin.PageView;
import com.weitu.util.AjaxResult;
import com.weitu.util.DateTimeUtil;
import com.weitu.util.IDGenerator;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static com.weitu.util.AjaxResult.fail;
import static com.weitu.util.AjaxResult.success;

/**
 * @author LiMeng 2017/4/13
 */
@Controller
@RequestMapping(value = "contractor/businessQualification")
public class BusinessQualificationController extends BaseController {
    private static final String MODULE_BATH_PATH = BASE_JSP_PATH + "contractor/businessQualification";
    private final BusinessQualificationService businessQualificationService;
    private final BusinessQualificationHistoryService businessQualificationHistoryService;

    @Autowired
    public BusinessQualificationController(BusinessQualificationService businessQualificationService,
                                           BusinessQualificationHistoryService businessQualificationHistoryService) {
        this.businessQualificationService = businessQualificationService;
        this.businessQualificationHistoryService = businessQualificationHistoryService;
    }

    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public Object businessListAjax(HttpServletRequest request, String sort, String contractorId) throws Exception {
        BusinessQualificationCriteria criteria = new BusinessQualificationCriteria();
        criteria.createCriteria()
                .andDelStateEqualTo(0)
                .andContractorIdEqualTo(contractorId);

        int count = businessQualificationService.countByCriteria(criteria);

        DataGridPagination dataGridPagination = DataGridPagination.getInstance(request, count);//获取分页对象
        PageView pageView = dataGridPagination.getPageView();//生成pageView分页对象
        //未传sort参数是采用添加时间排序
        if (StringUtils.isEmpty(sort)) {
            pageView.setSortColumn("addTime");
        } else {
            criteria.setOrderByClause(pageView.getSortColumn() + " " + pageView.getOrderType());
        }
        criteria.setPageView(pageView);

        List<BusinessQualification> businessQualifications = businessQualificationService.selectByCriteria(criteria);

        return dataGridPagination.flushDataGridData(businessQualifications);
    }

    @SystemLog(module = "承包商信息", methods = "更新上传业务资质附件")
    @ResponseBody
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public AjaxResult businessUploadAjax(String id, String contractorId) throws Exception {
        if (StringUtils.isEmpty(contractorId)) {
            return fail("添加失败！");
        }
        BusinessQualification businessQualification = new BusinessQualification();
        businessQualification.setId(id);
        businessQualification.setUpdateUserId(getSessionUser().getId());
        businessQualification.setUpdateDeptId(getSessionUser().getDepartment().getId());
        businessQualification.setUpdateTime(DateTimeUtil.formatterDateTime());
        businessQualification.setContractorId(contractorId);
        if (businessQualificationService.updateByPrimaryKeySelective(businessQualification) > 0) {
            if (!AccessoryUtil.saveAccerssoryInfo(id)) {
                return fail("附件信息保存失败！");
            }
            return success("保存成功！");
        }
        return fail("保存失败！");
    }

    @SystemLog(module = "承包商信息", methods = "添加业务资质信息")
    @ResponseBody
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public AjaxResult businessSaveAjax(String id, String contractorId) throws Exception {
        if (StringUtils.isEmpty(contractorId)) {
            return fail("添加失败！");
        }
        BusinessQualification businessQualification = new BusinessQualification();
        businessQualification.setId(id);
        businessQualification.setAddUserId(getSessionUser().getId());
        businessQualification.setAddDeptId(getSessionUser().getDepartment().getId());
        businessQualification.setAddTime(DateTimeUtil.formatterDateTime());
        businessQualification.setContractorId(contractorId);
        if (businessQualificationService.insertSelective(businessQualification) > 0) {
            return success("保存成功！");
        }
        return fail("保存失败！");
    }

    @SystemLog(module = "承包商信息", methods = "更新证书信息")
    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public AjaxResult businessUpdateAjax(BusinessQualification businessQualification) throws Exception {
        if (businessQualificationService.checkIfExtraExist(businessQualification.getContractorId(),
                businessQualification.getName(),
                businessQualification.getCertCode(),
                businessQualification.getId())) {
            return fail("保存失败，已有相同名称或编号的业务资质数据！");
        }
        businessQualification.setUpdateUserId(getSessionUser().getId());
        businessQualification.setUpdateDeptId(getSessionUser().getDepartment().getId());
        businessQualification.setUpdateTime(DateTimeUtil.formatterDateTime());
        if (businessQualificationService.updateByPrimaryKeySelective(businessQualification) > 0) {
            BusinessQualificationHistory history = new BusinessQualificationHistory();
            history.setId(IDGenerator.getId());
            history.setAddUserId(getSessionUser().getId());
            history.setAddDeptId(getSessionUser().getDepartment().getId());
            history.setAddTime(DateTimeUtil.formatterDateTime());
            history.setBusinessId(businessQualification.getId());
            history.setContractorId(businessQualification.getContractorId());
            history.setName(businessQualification.getName());
            history.setCertCode(businessQualification.getCertCode());
            history.setValidStartDate(businessQualification.getValidStartDate());
            history.setValidEndDate(businessQualification.getValidEndDate());
            businessQualificationHistoryService.insertSelective(history);
            return success("保存成功！");
        }
        return fail("保存失败！");
    }

    @SystemLog(module = "承包商信息", methods = "删除业务资质信息")
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public AjaxResult businessDeleteAjax(String id) throws Exception {
        if (businessQualificationService.deleteByPrimaryKey(id) > 0) {
            return success("删除成功！");
        }
        return fail("删除失败！");
    }

    @ResponseBody
    @RequestMapping(value = "/historyList", method = RequestMethod.POST)
    public Object businessHistoryListAjax(HttpServletRequest request, String businessId, String contractorId) throws Exception {
        BusinessQualificationHistoryCriteria criteria = new BusinessQualificationHistoryCriteria();
        criteria.createCriteria()
                .andDelStateEqualTo(0)
                .andContractorIdEqualTo(contractorId)
                .andBusinessIdEqualTo(businessId);

        int count = businessQualificationHistoryService.countByCriteria(criteria);

        DataGridPagination dataGridPagination = DataGridPagination.getInstance(request, count);//获取分页对象
        PageView pageView = dataGridPagination.getPageView();//生成pageView分页对象
        criteria.setPageView(pageView);

        List<BusinessQualificationHistory> businessQualificationHistories = businessQualificationHistoryService.selectByCriteria(criteria);

        return dataGridPagination.flushDataGridData(businessQualificationHistories);
    }
}
